package com.hopeland.androidpc.jilintongdaomen;

import java.util.List;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.GridView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.hopeland.androidpc.jilintongdaomen.uhf.UHFBaseActivity;
import com.hopeland.androidpc.jilintongdaomen.uhf.UHFMain;
import com.rfidread.Interface.IAsynchronousMessage;
import com.rfidread.Models.GPI_Model;
import com.rfidread.Models.Tag_Model;
import com.rfidread.RFIDReader;

import java.util.ArrayList;
import java.util.HashMap;
/**
 * 
 * @author RFID_C Demo主菜单
 */
public class ItemMainActivity extends UHFBaseActivity  implements
		IAsynchronousMessage {
	GridView gridView;
	//连接弹出框
	Spinner connectType = null;
	long connectTypeIndex=0; //选择的连接类型的索引
	EditText connectParam = null;
	Spinner bt4ConnectParam = null;
	String[] bt4DeviceName = null; //Bluetooth device name
	String connparam="";//连接参数

	ArrayList<HashMap<String ,Object>> listItemArrayList=new ArrayList<HashMap<String,Object>>();
	int listIndex = 0;//图标索引

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// 创建
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.item_main);

		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}

		gridView = (GridView) findViewById(R.id.main_item_grid);
		ChangeLayout(getResources().getConfiguration());
		try {
			getWindow().setFlags(
					WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
					WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		} catch (Exception ex) {
			Log.d("Debug", "The initialization of abnormal:" + ex.getMessage());
		}

		listItemArrayList.clear();

		if (true) { //UHF
			HashMap<String, Object> map = new HashMap<String,Object>();
			map.put("itemImage", R.drawable.uhf);
			map.put("itemText", getString(R.string.btn_MainMenu_UHF));
			map.put("itemActivity", UHFMain.class);
			listItemArrayList.add(map);
		}

//		if (true) { //HF
//			HashMap<String, Object> map=new HashMap<String,Object>();
//			map.put("itemImage", R.drawable.hf);
//			map.put("itemText", getString(R.string.btn_MainMenu_HF));
//			map.put("itemActivity", HFMain.class);
//			listItemArrayList.add(map);
//		}

		if (true) { // version
			HashMap<String, Object> map = new HashMap<String,Object>();
			map.put("itemImage", R.drawable.version);
			map.put("itemText", getString(R.string.btn_MainMenu_Version));
			map.put("itemActivity", null);
			listItemArrayList.add(map);
		}
		if (true) { // serial number
			HashMap<String, Object> map=new HashMap<String,Object>();
			map.put("itemImage", R.drawable.serialno);
			map.put("itemText", getString(R.string.btn_MainMenu_SerialNumber));
			map.put("itemActivity", null);
			listItemArrayList.add(map);
		}


		//生成适配器的ImageItem 与动态数组的元素相对应
		SimpleAdapter saImageItems = new SimpleAdapter(this,
				listItemArrayList,//数据来源
				R.layout.grid_item,//item的XML

				//动态数组与ImageItem对应的子项
				new String[]{"itemImage", "itemText"},

				//ImageItem的XML文件里面的一个ImageView,TextView ID
				new int[]{R.id.grid_item_image, R.id.grid_item_txt});
		//添加并且显示
		gridView.setAdapter(saImageItems);
		//添加消息处理
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				//Toast.makeText(getActivity(),name[position],Toast.LENGTH_LONG).show();
				if (isFastClick()) {
					return;
				}
                listIndex = position;
				HashMap<String, Object> map = listItemArrayList.get(listIndex);
				if (getString(R.string.btn_MainMenu_Version).equals(map.get("itemText"))) {
					GetVersion();
					return;
				}
				//其他选项，需先建立连接
				if(!_UHFSTATE)
				{
					onLogin();
					return;
				}
				//查询生产序列号
				if (map.get("itemText").equals(getString(R.string.btn_MainMenu_SerialNumber))) {
					GetSerialNumber();
					return;
				}
				Intent intent = new Intent();
				intent.setClass(ItemMainActivity.this, (Class<?>) map.get("itemActivity"));
				startActivity(intent);
			}
		});

		showCustomBar(getString(R.string.tv_MainMenu_Title),
				getString(R.string.str_exit), null,
				R.drawable.left, 0,
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Exit(v);
					}
				},
				null
		);
	}

	private void ChangeLayout(Configuration newConfig) {
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { //当前屏幕为横屏
			gridView.setNumColumns(4);
		} else { // 当前屏幕为竖屏
			gridView.setNumColumns(3);
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		ChangeLayout(newConfig);
	}

	//连接对话框
	protected void onLogin()
	{
		connparam = "/dev/ttyS3:115200";
		sendMessage(MSG_SHOW_WAIT,
				getString(R.string.str_please_waitting));
		String vStr = "Note:";
		boolean isConnectOK = false;
		if(InitConnect(connectTypeIndex,connparam)) //连接读写器
		{
			vStr = getString(R.string.str_LoginSuccess);
			isConnectOK = true;
		}
		else{
			vStr = getString(R.string.str_LoginFaild);
		}
		sendMessage(MSG_SHOW_TIP, vStr);
		sendMessage(MSG_HIDE_WAIT, null);
		//
		if(isConnectOK) {
			HashMap<String, Object> map = listItemArrayList.get(listIndex);

				Intent intentA = new Intent();
				intentA.setClass(ItemMainActivity.this, (Class<?>) map.get("itemActivity"));
				startActivity(intentA);

		}


	}

	//初始化
	protected boolean InitConnect(long index,String connparam)
	{
		boolean ret=false;

		if(Rfid_RS232_Init(connparam,this))
		{
			ret=true;
		}
		return ret;
	}

    //添加蓝牙名称
    private void AddBluetoothName()
    {
        connectParam.setVisibility(View.GONE);
        bt4ConnectParam.setVisibility(View.VISIBLE);
        List<String> listName = RFIDReader.GetBT4DeviceStrList();
        if(listName.size()>0){
            bt4DeviceName = listName.toArray(new String[listName.size()]);
            ArrayAdapter<String> bt4Adapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, bt4DeviceName);
            //将adapter添加到m_Spinner中
            bt4ConnectParam.setAdapter(bt4Adapter);
        }
    }

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if((!_UHFSTATE)&&(connectTypeIndex == 3)) //未连接且为蓝牙连接时
		{
            AddBluetoothName();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		UHF_Dispose();
		System.exit(0);
	}
    /**
     * 获取版本
     */
	public void GetVersion() {
	    try {
            String sdkVersion = RFIDReader.GetVER();
            showMsg("APP:" + getVersion() + "\n" + "SDK:" + sdkVersion + "\n", null);
        }
        catch (Exception ex){}
	}

	/**
	 * 获取读写器序列号
	 */
	public void GetSerialNumber() {
		try {
			String serial = RFIDReader._Config.GetSN(ConnID);
			showMsg(serial, null);
		}
		catch (Exception ex){}
	}

	/**
	 * 退出应用
	 */
	public void Exit(View v) {
        UHF_Dispose();
		ItemMainActivity.this.finish();
		System.exit(0);
	}


	@Override
	public void OutPutTags(Tag_Model arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void OutPutTagsOver(String connID) {
		// TODO Auto-generated method stub

	}

	@Override
	public void GPIControlMsg(String connID,GPI_Model gpi_model) {

	}

	@Override
	public void PortClosing(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void PortConnecting(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void WriteDebugMsg(String connID,String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void WriteLog(String connID,String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void OutPutScanData(String connID,byte[] scandata) {
		// TODO Auto-generated method stub
		//System.out.println(msg);
	}

}
